package croleta.core.file;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class JSONFile extends File {

	/**
	 * <b>JSONFile:</b><br>
	 * The Class initialization method.<br>
	 * It passes the given path to the super class {@link File}.<br>
	 * Then it parses the contents of this file by creating a new {@link JSONObject}.
	 * @param path the file's path.
	 * @throws ServletException
	 */
	public JSONFile(String path,ServletContext servletContext) throws ServletException {
		super(path, servletContext);
		parse(fileToString());
	}

	/**
	 * <b>childtoStringArray:</b><br>
	 * Turns the requested child to a string array.
	 * @param childName
	 * @return the requested child as a string array.
	 * @throws ServletException 
	 */
	public String[] childToStringArray(String childName) throws ServletException {
		try {
			JSONArray temp = getJSON().getJSONArray(childName);
			String[] tempArr = new String[temp.length()];
			for (int i=0; i<temp.length(); i++) {
				tempArr[i] = temp.getString(i);
			}
			return tempArr;
		} catch (JSONException e) { throw new ServletException("requested child doesn't exist inside this file", e.getCause());
		}
	}

	/**
	 * <b>childtoString:</b><br>
	 * Turns the requested child to a string array.
	 * @param childName
	 * @return the requested child as a string.
	 * @throws ServletException 
	 */
	public String childToString(String childName) throws ServletException {
		try {
			return getJSON().getString(childName);
		} catch (JSONException e) { throw new ServletException("requested child doesn't exist inside this file", e.getCause());
		}
	}
	
	private JSONObject json = null;
	/**
	 * <b>parse:</b><br>
	 * Parses the contents of this file by creating a new {@link JSONObject}.<br>
	 * Then it saves it to a private object for future use.
	 * @param s the file's contents.
	 * @throws ServletException
	 */
	private void parse(String s) throws ServletException {
		try {
			json = new JSONObject(s);
		} catch (JSONException e) { throw new ServletException("an Error during the json file parsing."+s, e.getCause());
		}
	}
	
	/**
	 * <b>getJSON:</b>
	 * @return the private object that contains the JSON representation of this file.
	 */
	public JSONObject getJSON() {
		return json;
	}
}
